/**
 * There are <a href="https://github.com/thinkgem/jeesite">JeeSite</a> code generation
 */
package com.boxin.ims.modules.wechat.service;

import java.io.File;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.boxin.framework.base.utils.Constants;
import com.boxin.framework.base.utils.DateUtils;
import com.boxin.ims.modules.momarketing.common.QRCodeUtils;
import com.boxin.ims.modules.momarketing.entity.QRCode;
import com.boxin.ims.modules.momarketing.service.QRCodeService;
import com.boxin.ims.modules.wechat.dao.LotteryRecordDao;
import com.boxin.ims.modules.wechat.entity.LotteryRecord;
import com.thinkgem.jeesite.common.persistence.BaseEntity;
import com.thinkgem.jeesite.common.persistence.Page;
import com.thinkgem.jeesite.common.service.BaseService;
import com.thinkgem.jeesite.common.utils.FileUtils;

/**
 * 中奖人记录Service
 * @author Jakemanse
 * @version 2013-09-23
 */
@Component
@Transactional(readOnly = true)
public class LotteryRecordService extends BaseService {

	@SuppressWarnings("unused")
	private static Logger logger = LoggerFactory.getLogger(LotteryRecordService.class);
	
	@Autowired
	private LotteryRecordDao lotteryRecordDao;
	
	@Autowired
	private QRCodeService qrCodeService;
	
	@Autowired
	private UserDefineService userDefineService;
	
	public LotteryRecord get(Long id) {
		return lotteryRecordDao.findOne(id);
	}
	
	public Page<LotteryRecord> find(Page<LotteryRecord> page, LotteryRecord lotteryRecord) {
		DetachedCriteria dc = lotteryRecordDao.createDetachedCriteria();
		dc.createAlias("member", "member");
		if (lotteryRecord.getUser()!=null && lotteryRecord.getUser().getId() != null){
			dc.add(Restrictions.eq("user.id", lotteryRecord.getUser().getId()));
		}
		
		
		if (lotteryRecord.getMember()!=null && lotteryRecord.getMember().getMobile() != null){
			dc.add(Restrictions.like("member.mobile", "%"+lotteryRecord.getMember().getMobile()+"%"));
		}
		
		if (lotteryRecord.getSourceType()!=null ){
			dc.add(Restrictions.eq("sourceType",lotteryRecord.getSourceType()));
		}
		
		if(lotteryRecord.getCreateTime() !=null){
			String timeField = "createTime";
			if (StringUtils.isNotEmpty(lotteryRecord.getStatus()) && BaseEntity.STATUS_CLEAR.equals(lotteryRecord.getStatus())){
				timeField = "updateTime";
			}
			dc.add(Restrictions.ge(timeField,lotteryRecord.getCreateTime() ));
		}
		
		if(lotteryRecord.getEndTime() !=null){
			String timeField = "createTime";
			if (StringUtils.isNotEmpty(lotteryRecord.getStatus()) && BaseEntity.STATUS_CLEAR.equals(lotteryRecord.getStatus())){
				timeField = "updateTime";
			}
			dc.add(Restrictions.le(timeField,lotteryRecord.getEndTime()));
		}
		
		if (StringUtils.isNotEmpty(lotteryRecord.getStatus())){
			dc.add(Restrictions.like("status", "%"+lotteryRecord.getStatus()+"%"));
		}
		if (StringUtils.isNotEmpty(lotteryRecord.getName())){
			dc.add(Restrictions.like("name", "%"+lotteryRecord.getName()+"%"));
		}
		if (StringUtils.isNotEmpty(lotteryRecord.getRemarks())){
			dc.add(Restrictions.like("remarks", "%"+lotteryRecord.getRemarks()+"%"));
		}
		dc.add(Restrictions.eq("delFlag", LotteryRecord.DEL_FLAG_NORMAL));
		dc.addOrder(Order.desc("id"));
		return lotteryRecordDao.find(page, dc);
	}
	
	/**
	 * @author Jakemanse
	 * @time 2014-5-8  上午9:57:16
	 * @function <p> 查询 会员获得某类型的奖品数量 </p>
	 * @param lotteryRecord
	 * @return
	 */
	public Long findLotteryRecordCountBySourceType(LotteryRecord lotteryRecord){
		
		DetachedCriteria dc = lotteryRecordDao.createDetachedCriteria();
		dc.createAlias("member", "member");
		if (lotteryRecord.getUser()!=null && lotteryRecord.getUser().getId() != null){
			dc.add(Restrictions.eq("user.id", lotteryRecord.getUser().getId()));
		}
		
		if(lotteryRecord.getMember()!=null && lotteryRecord.getMember().getId()>0){
			dc.add(Restrictions.eq("member.id", lotteryRecord.getMember().getId()));
		}
		
		if(lotteryRecord.getSourceType()!= null){
			dc.add(Restrictions.eq("sourceType", lotteryRecord.getSourceType()));
		}
		
		dc.add(Restrictions.eq("delFlag", LotteryRecord.DEL_FLAG_NORMAL));
		
		return lotteryRecordDao.count(dc);
		
	}
	
	
	
	/**
	 * @author Jakemanse
	 * @time 2014-4-30  上午10:37:48
	 * @function <p> 查找广告奖品 </p>
	 * @param memberId
	 * @param advertId
	 * @return
	 */
	public List<LotteryRecord> findByMemberIdAndAdvertId(Long memberId,Long advertId){
		DetachedCriteria dc = lotteryRecordDao.createDetachedCriteria();
		dc.createAlias("member", "member");
		
		dc.add(Restrictions.eq("member.id", memberId));
		dc.add(Restrictions.eq("sourceId", advertId));
		
		
		return lotteryRecordDao.find( dc);
	}
	
	
	
	/**
	 * @author Jakemanse
	 * @time 2014-5-8  上午9:57:16
	 * @function <p> 查询 会员获得某类型的奖品数量 </p>
	 * @param lotteryRecord
	 * @return
	 */
	public int findLotteryRecordCount(LotteryRecord lotteryRecord){
		
		DetachedCriteria dc = lotteryRecordDao.createDetachedCriteria();
		dc.createAlias("member", "member");
		if (lotteryRecord.getUser()!=null && lotteryRecord.getUser().getId() != null){
			dc.add(Restrictions.eq("user.id", lotteryRecord.getUser().getId()));
		}
		
		if(lotteryRecord.getMember()!=null && lotteryRecord.getMember().getId()>0){
			dc.add(Restrictions.eq("member.id", lotteryRecord.getMember().getId()));
		}
		
		if(lotteryRecord.getSourceType()!= null){
			dc.add(Restrictions.eq("sourceType", lotteryRecord.getSourceType()));
		}
		
		dc.add(Restrictions.eq("delFlag", LotteryRecord.DEL_FLAG_NORMAL));
		
		
		List<LotteryRecord> list = lotteryRecordDao.find( dc);
		
		return list.size();
		
	}
	
	
	
	
	public List<LotteryRecord>  find( LotteryRecord lotteryRecord){
		DetachedCriteria dc = lotteryRecordDao.createDetachedCriteria();
		dc.createAlias("member", "member");
		if (lotteryRecord.getUser()!=null && lotteryRecord.getUser().getId() != null){
			dc.add(Restrictions.eq("user.id", lotteryRecord.getUser().getId()));
		}
		
		
		if (lotteryRecord.getMember()!=null && lotteryRecord.getMember().getMobile() != null){
			dc.add(Restrictions.eq("member.mobile", lotteryRecord.getMember().getMobile()));
		}
		
		if (lotteryRecord.getSourceType()!=null ){
			dc.add(Restrictions.eq("sourceType",lotteryRecord.getSourceType()));
		}
		if (lotteryRecord.getCreateTime()!=null ){
			dc.add(Restrictions.ge("createTime",lotteryRecord.getCreateTime()));
		}
		
		if (StringUtils.isNotEmpty(lotteryRecord.getStatus())){
			dc.add(Restrictions.eq("status", lotteryRecord.getStatus() ));
		}
		if (StringUtils.isNotEmpty(lotteryRecord.getName())){
			dc.add(Restrictions.like("name", "%"+lotteryRecord.getName()+"%"));
		}
		if (StringUtils.isNotEmpty(lotteryRecord.getRemarks())){
			dc.add(Restrictions.like("remarks", "%"+lotteryRecord.getRemarks()+"%"));
		}
		dc.add(Restrictions.eq("delFlag", LotteryRecord.DEL_FLAG_NORMAL));
		dc.addOrder(Order.desc("id"));
		return lotteryRecordDao.find( dc);
	}
	
	@Transactional(readOnly = false)
	public void save(LotteryRecord lotteryRecord) {
		
		int width = QRCodeUtils.WIDTH;
		int height =QRCodeUtils.HEIGHT;
		//生成二维码
		QRCode qrcode = new QRCode();
		String content = QRCodeUtils.generateLotterySN(lotteryRecord.getUser().getId());
		qrcode.setContent(content);
		String path = Constants.getWechatResourceSavePath();
		path += DateUtils.getTodayString()+File.separator+content;
		FileUtils.createDirectory(path);
		QRCodeUtils.generateQRCodePNG(content, path, width,height);
		qrcode.setFileName(content+".png");
		qrcode.setPngPath(path+".png");
		
		qrcode.setUser(lotteryRecord.getUser());
		qrcode.setMember(lotteryRecord.getMember());
		qrcode.setType(lotteryRecord.getSourceType());
		qrcode.setName(lotteryRecord.getName());
		
		qrCodeService.save(qrcode);	//保存二维码		
		
		lotteryRecord.setQrCode(qrcode);
		lotteryRecordDao.save(lotteryRecord);
	}
	
	@Transactional(readOnly = false)
	public void delete(Long id) {
		lotteryRecordDao.deleteById(id);
	}
	
	@Transactional(readOnly = false)
	public void updateStatusById(Long id,String status) {
		lotteryRecordDao.updateStatusById(id,status);
	}
	
	/**
	 * @author Jakemanse
	 * @time 2013-12-12  上午1:00:00
	 * @function <p> 核销注册会员礼品  </p>
	 * @param userId
	 * @param memberId
	 * @param remarks
	 */
	public int updateRegLotteryStatus(Long userId,Long memberId,String remarks){
		return lotteryRecordDao.updateRegLotteryStatus(userId,memberId,remarks);
	}
	
	
	/**
	 * @author Jakemanse
	 * @time 2013-12-12  上午1:09:32
	 * @function <p> 获取注册会员大礼品 </p>
	 * @param userId
	 * @param memberId
	 * @return
	 */
	public LotteryRecord getRegLotteryByUserIdMemberId(Long userId,Long memberId){
		return lotteryRecordDao.getRegLotteryByUserIdMemberId(userId, memberId);
	}
	
}
